package com.tm.exception.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

// 加密算法  md5
public class MD5Utils {

    public static void main(String[] args) {
        // 给明文  得到加密后的字符串  a     密码  1234    盐  aaa  （私有 唯一）
        //  244dfbbe69ac463c6e605fabef3e89d0
                                    // b    1234       盐   bbb （私有 唯一）
        // 6d1244be45f46c63f1fb240f65c79fee
        // 加密  +加盐   现在普遍流行的
        String s = MD5Utils.md5("1234");
        String s1 = MD5Utils.md5(s + "aaa");
        System.out.println(s1);

          String s2 = MD5Utils.md5("1234");
        String s3 = MD5Utils.md5(s + "bbb");
        System.out.println(s3);


    }

    private static final char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
            'b', 'c', 'd', 'e', 'f'};

    /**
     * 对字符串进行MD5加密
     *
     * @param text 明文
     * @return 密文
     */
    public static String md5(String text) {
        MessageDigest msgDigest = null;
        try {
            msgDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("System doesn't support MD5 algorithm.");
        }
        try {
            msgDigest.update(text.getBytes("UTF-8")); // 注意该接口是按照指定编码形式签名
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("System doesn't support your  EncodingException.");
        }
        byte[] bytes = msgDigest.digest();

        String md5Str = new String(encodeHex(bytes));

        return md5Str;
    }
    private static char[] encodeHex(byte[] data) {
        int l = data.length;
        char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS[0x0F & data[i]];
        }
        return out;
    }
}
